// pkgUser/pages/chat/index.js
import {
  getMsgList,
  sendMsg
} from '../../../api/ChatMsgController.js'
import dayjs from 'dayjs'
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    scrollTop: 0, //距离顶部多少
    scrollY: true,
    bottom: 0, // 输入框距离页面底部距离（键盘高度px）
    bottomP: 0, //针对ipone手机底部安全距离
    triggered: false, //设置当前下拉刷新状态
    time: '0-00 00:00', //当前时间
    msgList: [], //聊天信息列表
    totalPage: 0, //数据总页数
    params: {
      pageNum: 1,
      pageSize: 10,
      fromId: wx.getStorageSync('userId'),
      toId: '',
    },
    value: '', //输入框内容
    count: 0
  },
  //滚动到页面底部
  scrollBottom() {
    let query = wx.createSelectorQuery().in(this)
    query.select('.msg-list').boundingClientRect(res => {
      this.setData({
        scrollTop: res.height + 200
      })
    })
    query.exec(res => {})
  },
  //滚动到页面顶部
  scrollTop() {
    if (this.data.params.pageNum === this.data.totalPage) return this.setData({
      triggered: false
    })
    this.setData({
      'params.pageNum': this.data.params.pageNum + 1
    })
    this.getMessageList().then(() => {
      this.setData({
        triggered: false
      })
    })

  },
  //获取私聊聊天列表
  async getMessageList() {
    const res = await getMsgList(this.data.params)
    this.setData({
      msgList: [...res.list, ...this.data.msgList],
      totalPage: res.totalPage
    })
  },
  //发送消息
  async send() {
    const content = this.data.value
    const {
      fromId,
      toId
    } = this.data.params
    const res = await sendMsg({
      fromId,
      toId,
      content
    })

    this.setData({
      msgList: [...this.data.msgList, res],
      value: ''
    })

    this.scrollBottom()
  },
  inputValueChange() {},
  // //弹出键盘输入框上移
  // inputFocus(e) {
  //   this.setData({
  //     bottom: e.detail.height - 1,
  //     scrollY: false
  //   })
  //   wx.pageScrollTo({
  //     scrollTop: 9999
  //   })
  // },
  // //输入框下移
  // inputBlur() {
  //   this.setData({
  //     bottom: 0,
  //     scrollY: true
  //   })
  // },
  //去主页
  toOtherPersonalHome(e) {
    wx.navigateTo({
      url: '/pkgUser/pages/otherPersonalHome/index?userId=' + e.mark.userId,
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad({
    userId,
    nickName,
    count
  }) {
    if (count) this.setData({
      count,
    })
    wx.getSystemInfo({
      success: res => {
        this.setData({
          bottomP: res.screenHeight - res.safeArea.bottom
        })
      }
    })
    //接收消息
    wx.onSocketMessage((data) => {
      if (!data.data) return
      const msg = JSON.parse(data.data)
      if (msg.fromId !== this.data.params.toId) return
      this.setData({
        msgList: [...this.data.msgList, msg],
        count: this.count + 1
      })
      this.scrollBottom()
    })
    const title = nickName === 'undefined' ? '微信用户' : nickName
    wx.setNavigationBarTitle({
      title,
    })
    this.setData({
      time: dayjs().format('M-DD HH:mm'),
      'params.toId': userId
    })
    this.getMessageList(userId)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.scrollBottom()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.sendSocketMessage({
      data: JSON.stringify({
        type: '1',
        fromId: wx.getStorageSync('userId'),
        toId: this.data.params.toId
      }),
      success: (res) => {},
    })
    app.count = app.count >= this.data.count ? app.count - this.data.count : 0
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})